package com.cheer.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.bo.PrizeBO;
import com.cheer.config.OrgOfficeConstant;
import com.cheer.dao.ExMatchAwardDao;
import com.cheer.dao.ExMatchAwardRecordDao;
import com.cheer.dao.ExMatchHistoryDao;
import com.cheer.dao.ExMatchUserDao;
import com.cheer.entity.ExMatchAwardEntity;
import com.cheer.entity.ExMatchUserEntity;
import com.cheer.enums.AwardEnum;
import com.cheer.enums.LotteryActTypeEnum;
import com.cheer.exception.ServiceException;
import com.cheer.param.AwardUpdateParam;
import com.cheer.service.ExMatchAwardService;
import com.cheer.utils.BeanUtil;
import com.cheer.utils.ExcelsUtil;
import com.cheer.vo.AwardListVO;
import com.cheer.vo.PrizeVO;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service("exMatchAwardService")
public class ExMatchAwardServiceImpl extends ServiceImpl<ExMatchAwardDao, ExMatchAwardEntity> implements ExMatchAwardService {

    @Autowired
    private ExMatchUserDao exMatchUserDao;

    @Autowired
    private ExMatchHistoryDao exMatchHistoryDao;

    @Autowired
    private ExMatchAwardRecordDao exMatchAwardRecordDao;

    @Override
    public void exportMatchHistory() {

        List<Map<String, Object>> excelList = new ArrayList<>();
        Map<String, Object> header = new HashMap<>();
        String sheet = "参与情况";
        header.put("sheetName", sheet);
        excelList.add(header);

        for (int i = 0; i < OrgOfficeConstant.organization.length; i++) {
            for (int j = 0; j < OrgOfficeConstant.office[i].length; j++) {

                int organization = i;
                int office = j + 1;

                if (i == OrgOfficeConstant.organization.length - 1 && j == OrgOfficeConstant.office[i].length - 1) {
                    office = 100;
                }

                Integer count = exMatchUserDao.selectCount(new QueryWrapper<ExMatchUserEntity>()
                        .eq("organization", organization)
                        .eq("office", office));

                Integer mat = exMatchHistoryDao.selectCountByOrg(organization, office);

                Map<String, Object> line = new HashMap<>();
                line.put("org", OrgOfficeConstant.organization[i] + "-" + OrgOfficeConstant.office[i][j]);
                line.put("reg", count);
                line.put("mat", mat);
                excelList.add(line);
            }
        }

        String[] columnNames = {"单位", "注册人数", "参与人数"};
        String[] keys = {"org", "reg", "mat"};
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        ExcelsUtil.ExcelSingleOutputStream(excelList, keys, columnNames, sheet, request, response);

    }

    @Override
    public List<AwardListVO> list(Integer act) {
        List<ExMatchAwardEntity> list = list();
        List<AwardListVO> awardListVOS = BeanUtil.batchTransform(AwardListVO.class, list);
        awardListVOS.stream().forEach((awardListVO) -> awardListVO.setAtcNameByAct());
        return awardListVOS;
    }

    @Override
    public void update(AwardUpdateParam awardParam) {

        if( awardParam.getStartPut() != null
                && awardParam.getEndPut() != null ){
            if(awardParam.getEndPut().compareTo(awardParam.getStartPut()) == -1){
                throw new ServiceException("投放开始时间不得小于投放结束时间！");
            }
        }
        Long awardId = awardParam.getId();
        ExMatchAwardEntity exMatchAwardEntity = getById(awardId);
        if(exMatchAwardEntity == null){
            throw new ServiceException(" 未查询到要修改的记录！");
        }
        ExMatchAwardEntity updateRecode = BeanUtil.transform(ExMatchAwardEntity.class,  awardParam);
        updateById(updateRecode);
    }


    @Override
    public void exportPrize() {

        Map<Long, ExMatchAwardEntity> awardEntityMap = list().stream().collect(Collectors.toMap(ExMatchAwardEntity::getId, Function.identity()));
        List<PrizeVO> prizeVOList = getPrize();

        List<Map<String, Object>> excelList = new ArrayList<>();
        Map<String, Object> header = new HashMap<>();
        String sheet = "中奖信息";
        header.put("sheetName", sheet);
        excelList.add(header);

        for (PrizeVO prizeVO : prizeVOList) {

            ExMatchAwardEntity exMatchAward = awardEntityMap.get(prizeVO.getAwardId());
            if(exMatchAward == null){
                log.error(" 未查询到当前奖品ID ：" + prizeVO.getAwardId());
                continue;
            }
            Map<String, Object> line = new HashMap<>();
            line.put("username", prizeVO.getUsername());
            line.put("actName",  exMatchAward.getActName());
            line.put("prize", awardEntityMap.get(prizeVO.getAwardId()).getAwardName());
            line.put("phone", prizeVO.getPhone());
            line.put("address", prizeVO.getAddress());
            line.put("createTime", DateUtil.format(prizeVO.getCreateTime(),"yyyy-MM-dd"));
            excelList.add(line);
        }

        String[] columnNames = {"姓名",  "活动" ,"奖品", "联系方式", "中奖地址", "中奖日期"};
        String[] keys = {"username", "actName","prize", "phone", "address", "createTime"};
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        ExcelsUtil.ExcelSingleOutputStream(excelList, keys, columnNames, sheet, request, response);
    }

    @Override
    public AwardListVO info(Integer id) {

        ExMatchAwardEntity exMatchAwardEntity = getById(id);
        if(exMatchAwardEntity == null){
            throw new ServiceException("参数异常ID值不能为空！");
        }
        AwardListVO awardListVO = BeanUtil.transform(AwardListVO.class, exMatchAwardEntity);
        awardListVO.setAtcNameByAct();
        return awardListVO;
    }

    private List<PrizeVO> getPrize() {

        List<PrizeBO> prizeBOList = exMatchAwardRecordDao.getPrize();
        List<PrizeVO> prizeVOList = new ArrayList<>();
        for (PrizeBO prizeBO : prizeBOList) {
            PrizeVO prizeVO = new PrizeVO().setUsername(prizeBO.getUsername())
                    .setPhone(prizeBO.getPhone())
                    .setAct(prizeBO.getAct())
                    .setAwardId(prizeBO.getAwardId())
                    .setCreateTime(prizeBO.getCreateTime());

            if (StringUtils.isNotBlank(prizeBO.getProvince()) && StringUtils.isNotBlank(prizeBO.getCity()) &&
                    StringUtils.isNotBlank(prizeBO.getRegion()) && StringUtils.isNotBlank(prizeBO.getAddress())) {
                if (StringUtils.equals(prizeBO.getProvince(), prizeBO.getCity())) {
                    prizeVO.setAddress(StringUtils.join(Lists.newArrayList(
                            prizeBO.getCity(), prizeBO.getRegion(), prizeBO.getAddress()), "，"));
                } else {
                    prizeVO.setAddress(StringUtils.join(Lists.newArrayList(prizeBO.getProvince(),
                            prizeBO.getCity(), prizeBO.getRegion(), prizeBO.getAddress()), "，"));
                }
            }
            prizeVOList.add(prizeVO);
        }

        return prizeVOList;
    }

}
